package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.UserLoginSuccessVo;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;


/**
 * UserService
 *
 * @author liudo
 * @version 1.0
 * @project heima-leadnews
 * @date 2023/11/3 11:17:12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {
    @Override
    public UserLoginSuccessVo login(ApUser apUser) {
        if (StringUtils.isNoneBlank(apUser.getPhone(), apUser.getPassword())) {
            //  正常用户的登录
            ApUser apUserByPhone = baseMapper.selectOne(
                    Wrappers.lambdaQuery(ApUser.class)
                            .eq(ApUser::getPhone, apUser.getPhone())
            );
            if (Objects.isNull(apUserByPhone)) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            // 加盐判断
            String newPas = apUser.getPassword() + apUserByPhone.getSalt();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(newPas.getBytes());
            if (!Objects.equals(md5DigestAsHex, apUserByPhone.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //     3. 结果封装和返回
            String token = AppJwtUtil.generateToken(Long.valueOf(apUserByPhone.getId()));
            apUserByPhone.setPassword(null);
            apUserByPhone.setSalt(null);
            UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo();
            userLoginSuccessVo.setUser(apUserByPhone);
            userLoginSuccessVo.setToken(token);
            return userLoginSuccessVo;
        }
        //  游客的登录 - 没有手机号和密码
        String token = AppJwtUtil.generateToken(0L);
        UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo();
        userLoginSuccessVo.setToken(token);
        return userLoginSuccessVo;
    }
}
